package cn.mzcode.recheck.util;

import de.innosystec.unrar.Archive;
import de.innosystec.unrar.NativeStorage;
import de.innosystec.unrar.rarfile.FileHeader;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Enumeration;

/**
 * @author: 马壮
 * @create: 2020-04-28 22:45
 * @description: 解压工具类 支持zip和rar
 */
public class ZipAndRarUtil {

    private static final Logger log = LoggerFactory.getLogger(ZipAndRarUtil.class);

    /**
     * 解压rar
     *
     * @param sourceRarPath 需要解压的rar文件全路径
     * @param destDirPath   需要解压到的文件目录
     * @return 是否解压成功
     */
    public static boolean unrar(String sourceRarPath, String destDirPath) {
        File sourceRar = new File(sourceRarPath);
        File destDir = new File(destDirPath);
        try (Archive archive = new Archive(new NativeStorage(sourceRar))) {
            FileHeader fh = archive.nextFileHeader();
            File destFileName = null;
            while (fh != null) {
                String compressFileName = fh.getFileNameString().trim();
                destFileName = new File(destDir.getAbsolutePath() + "/" + compressFileName);
                if (fh.isDirectory()) {
                    if (!destFileName.exists()) {
                        destFileName.mkdirs();
                    }
                    fh = archive.nextFileHeader();
                    continue;
                }
                if (!destFileName.getParentFile().exists()) {
                    destFileName.getParentFile().mkdirs();
                }
                try (FileOutputStream fos = new FileOutputStream(destFileName)) {
                    archive.extractFile(fh, fos);
                } catch (Exception e) {
                    throw e;
                }
                fh = archive.nextFileHeader();
            }
            return true;
        } catch (Exception e) {
            log.error("[ZipAndRarUtil][unrar]解压rar出现异常,fileName={}", sourceRarPath, e);
            return false;
        }
    }


    /**
     * 解压Zip文件
     *
     * @param zipFileName  需要解压缩的文件位置
     * @param descFileName 将文件解压到某个路径
     * @return 是否解压成功
     */
    public static boolean unzip(String zipFileName, String descFileName) {
        try (ZipFile zip = new ZipFile(new File(zipFileName))) {
            File pathFile = new File(descFileName);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            for (Enumeration entries = zip.getEntries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String zipEntryName = entry.getName();
                String outPath = (descFileName + zipEntryName).replaceAll("\\*", "/");
                File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if (!file.exists()) {
                    file.mkdirs();
                }
                if (new File(outPath).isDirectory()) {
                    continue;
                }
                try (InputStream in = zip.getInputStream(entry);
                     OutputStream out = new FileOutputStream(outPath)) {
                    byte[] buf1 = new byte[1024];
                    int len;
                    while ((len = in.read(buf1)) > 0) {
                        out.write(buf1, 0, len);
                    }
                } catch (Exception e) {
                    throw e;
                }
            }
            return true;
        } catch (IOException e) {
            log.error("[ZipAndRarUtil][unzip]解压zip出现异常,fileName={}", zipFileName, e);
            return false;
        }
    }
}